const cluster = require("cluster");
const cpus = require("os").cpus();

exports.done = (callback) => {
  if (cluster.isMaster) {
    cpus.forEach(function () {
      cluster.schedulingPolicy = cluster.SCHED_NONE;
      var work_process = cluster.fork();
      work_process.on("message", function (msg) {
        //console.log('get message: ' + msg.cmd)
      });
    });

    cluster.on("death", function () {
      console.log("[master] " + worker.pid + " died. restart...");
      process.nextTick(function () {
        cluster.fork();
      });
    });

    cluster.on("fork", function (worker) {
      console.log("[master] " + "fork: worker" + worker.id);
    });

    cluster.on("online", function (worker) {
      console.log("[master] " + "online: worker" + worker.id);
    });

    cluster.on("listening", function (worker, address) {
      console.log(
        "[master] " +
          "listening: worker" +
          worker.id +
          ",pid:" +
          worker.process.pid +
          ", Address:" +
          address.address +
          ":" +
          address.port
      );
    });

    cluster.on("disconnect", function (worker) {
      console.log("[master] " + "disconnect: worker" + worker.id);
    });

    cluster.on("exit", function (worker, code, signal) {
      console.log("[master] " + "exit worker" + worker.id + " died");
    });
  } else if (cluster.isWorker) {
    console.log("[worker] " + "start worker ..." + cluster.worker.id);
    process.on("message", function (msg) {
      console.log("[worker] " + msg);
      process.send("[worker] worker" + cluster.worker.id + " received!");
    });
    callback && callback();
  }
};
